package com.online.shopping.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.online.shopping.custom.Specification;
import com.online.shopping.entity.RespBean;
import com.online.shopping.entity.ResultPage;
import com.online.shopping.pojo.TbSpecification;
import com.online.shopping.service.SpecificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/specification_Ms")
public class SpecificationController {

	@Autowired
	private SpecificationService specificationService;

	@GetMapping("/findAll")
	public ResultPage findAll(int pageNum, int pageSize){
		System.out.println("页码："+pageNum);
		System.out.println("每页记录数："+pageSize);

		PageHelper.startPage(pageNum, pageSize);
		Page<TbSpecification> page = (Page<TbSpecification>) specificationService.findAllTbSpecification();

		ResultPage resultPage = new ResultPage();
		resultPage.setRows(page.getResult());
		resultPage.setTotal(page.getTotal());

		return resultPage;
	}

	@GetMapping("/findSpecificationById/{id}")
	public Specification findSpecificationById(@PathVariable Long id){
		return specificationService.findSpecificationById(id);
	}

	@PostMapping("/add")
	public RespBean add(@RequestBody Specification specification){
		SpecificationController.printSpecification(specification);

		try{
			specificationService.add(specification);
			return RespBean.ok("添加成功！");
		} catch (Exception e){
			e.printStackTrace();
			return RespBean.error("添加失败！");
		}
	}

	@PostMapping("/update")
	public RespBean update(@RequestBody Specification specification){
		SpecificationController.printSpecification(specification);

		try{
			specificationService.update(specification);
			return RespBean.ok("修改成功！");
		} catch (Exception e){
			e.printStackTrace();
			return RespBean.error("修改失败！");
		}
	}

	private static void printSpecification(Specification specification){
		System.out.println("specification id: "+specification.getSpecification().getId());
		System.out.println("specification getOptionName: ");
		specification.getSpecificationOptionList().forEach(option->System.out.println(option.getOptionName()));
	}

	@PostMapping("/delete")
	public RespBean delete(@RequestBody Long[] ids){
		System.out.println("id[]: "+ids);

		try{
			specificationService.delete(ids);
			return RespBean.ok("删除成功！");
		} catch (Exception e){
			e.printStackTrace();
			return RespBean.error("删除失败！");
		}
	}

	@GetMapping("/findSpecList")
	public List findSpecList(){
		return specificationService.findSpecList();
	}
}
